<template>
  <div class="entries-add-container">
    <!-- 顶部导航栏 -->
    <VanNavBar
        title="发布词条"
        class="entries-add-header"
        :border="false"
        left-arrow
        @click-left="goBack"
    />

    <!-- 内容区域 -->
    <div class="content-wrapper">
      <!-- 发布表单 -->
      <div class="publish-form">
        <!-- 标题输入 -->
        <div class="form-group">
          <label class="form-label">词条标题</label>
          <VanField
              v-model="entriesForm.entryName"
              placeholder="请输入词条标题（5-50字）"
              :maxlength="50"
              show-word-limit
              class="title-input"
          />
        </div>

        <!-- 分类选择 -->
        <div class="form-group">
          <label class="form-label">分类</label>
          <VanField
              name="category"
              is-link
              v-model="selectedCategoryName"
              readonly
              placeholder="请选择分类"
              @click="showCategoryPicker = true"
              class="category-field"
          />
          <VanPopup v-model:show="showCategoryPicker" round position="bottom">
            <VanPicker
                v-model="selectedCategoryId"
                :columns="categoryColumns"
                @confirm="onCategoryConfirm"
                title="选择分类"
            />
          </VanPopup>
        </div>

        <!-- 来源输入 -->
        <div class="form-group">
          <label class="form-label">来源（可选）</label>
          <VanField
              v-model="entriesForm.source"
              placeholder="请输入词条来源"
              :maxlength="100"
              show-word-limit
              class="source-input"
          />
        </div>

        <!-- 内容输入 -->
        <div class="form-group">
          <label class="form-label">词条内容</label>
          <VanField
              v-model="entriesForm.description"
              type="textarea"
              placeholder="请输入词条内容（10-1000字）"
              :maxlength="1000"
              show-word-limit
              rows="8"
              class="content-input"
          />
        </div>

        <!-- 图片上传 -->
        <div class="form-group">
          <label class="form-label">词条图片</label>
          <div class="image-upload-section">
            <!-- 已选图片预览 -->
            <div v-if="entriesForm.entriesPic" class="image-preview">
              <img :src="entriesForm.entriesPic" alt="词条图片" />
              <VanIcon name="clear" class="delete-icon" @click="removeImage" />
            </div>

            <!-- 图片选择按钮 -->
            <div v-else class="upload-btn" @click="selectImage">
              <input
                  ref="fileInput"
                  type="file"
                  accept="image/*"
                  style="display: none"
                  @change="handleFileChange"
              />
              <VanIcon name="plus" size="24" />
              <span>选择图片</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部发布按钮 -->
    <div class="footer-actions">
      <VanButton
          round
          block
          type="primary"
          size="large"
          @click="handlePublish"
          :loading="loading"
          class="publish-btn"
      >
        {{ loading ? '发布中...' : '发布词条' }}
      </VanButton>
    </div>
    <!-- 加载中状态 -->
    <VanOverlay :show="loading" class="loading-overlay">
      <VanLoading size="48px" type="spinner" color="#07c160">发布中...</VanLoading>
    </VanOverlay>
    <tabbar/>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from '../utils/axios.js';
import { client, getFileNameUUID } from '../utils/alioss.ts';
import {useUserStore} from "@/stores/user.js";
import tabbar from '@/components/tab-bar.vue'

const router = useRouter();
const fileInput = ref(null);
const loading = ref(false);
const showCategoryPicker = ref(false);
// 确保初始值为数组
const selectedCategoryId = ref([]);
const selectedCategoryName = ref('');
const categoryColumns = ref([]);

// 添加组件挂载状态
const isMounted = ref(true);

// 词条表单数据
const entriesForm = reactive({
  entryName: '',
  description: '',
  categoryId: null,
  categoryName: '',
  source: '',
  entriesPic: ''
});

// 组件卸载时设置标志
onUnmounted(() => {
  isMounted.value = false;
});

// 返回上一页
const goBack = () => {
  router.back();
};

// 页面加载时获取分类列表
onMounted(async () => {
  try {
    const res = await axios.get('api/categories/list');
    if (res && isMounted.value) {
      categoryColumns.value = (res || []).map(item => ({
        text: item.categoryName || '',
        value: item.categoryId !== undefined ? item.categoryId : ''
      }));
      console.log('分类数据加载完成:', categoryColumns.value); // 确认有数据
    }
  } catch (error) {
    console.error('获取分类列表失败:', error);
  }
});

// 选择图片
const selectImage = () => {
  fileInput.value?.click();
};

// 处理文件选择
const handleFileChange = async (event) => {
  const file = event.target.files[0];
  if (!file) return;

  const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
  if (!validTypes.includes(file.type)) {
    return alert('请选择有效的图片文件（JPG、PNG、GIF、WEBP）');
  }

  if (file.size > 5 * 1024 * 1024) {
    return alert('图片大小不能超过5MB');
  }

  try {
    loading.value = true;
    const imageUrl = await uploadImageToOSS(file);

    // 检查组件是否仍然挂载
    if (isMounted.value) {
      entriesForm.entriesPic = imageUrl;
      event.target.value = '';
    }
  } catch (error) {
    console.error('上传图片失败:', error);
    if (isMounted.value) {
      alert('上传图片失败，请重试');
    }
  } finally {
    if (isMounted.value) {
      loading.value = false;
    }
  }
};

// 上传图片到阿里云OSS
const uploadImageToOSS = async (file) => {
  try {
    const ossClient = client();
    const fileName = getFileNameUUID();
    const fileExtension = file.name.split('.').pop().toLowerCase();
    const objectName = `entries/${fileName}.${fileExtension}`;

    const result = await ossClient.put(objectName, file);
    return `https://${ossClient.options.bucket}.oss-cn-hangzhou.aliyuncs.com/${result.name}`;
  } catch (error) {
    console.error('OSS上传失败:', error);
    throw error;
  }
};

// 移除图片
const removeImage = () => {
  entriesForm.entriesPic = '';
};

// 分类选择确认 - 修复：确保传入数组格式
const onCategoryConfirm = (event) => {
  // 从事件对象中直接获取选择数据
  const { selectedValues, selectedOptions } = event;

  // 验证数据有效性
  if (!selectedValues || !selectedOptions || selectedValues.length === 0 || selectedOptions.length === 0) {
    console.error('未获取到有效的选择值:', event);
    showCategoryPicker.value = false;
    return;
  }

  // 提取选中的值和选项对象（单列选择，取第一个元素）
  const selectedValue = selectedValues[0];
  const selectedOption = selectedOptions[0];

  // 更新选择状态和表单数据
  selectedCategoryId.value = [selectedValue];
  selectedCategoryName.value = selectedOption.text;
  entriesForm.categoryId = selectedValue;
  entriesForm.categoryName = selectedOption.text;

  console.log('分类选择成功:', {
    选中值: selectedValue,
    显示文本: selectedOption.text,
    表单中的分类ID: entriesForm.categoryId
  });

  showCategoryPicker.value = false;
};

// 验证表单
const validateForm = () => {
  if (!entriesForm.entryName.trim() || entriesForm.entryName.length < 5 || entriesForm.entryName.length > 50) {
    alert('请输入5-50字的词条标题');
    return false;
  }

  if (!entriesForm.categoryId) {
    alert('请选择词条分类');
    return false;
  }

  if (!entriesForm.description.trim() || entriesForm.description.length < 10 || entriesForm.description.length > 1000) {
    alert('请输入10-1000字的词条内容');
    return false;
  }

  return true;
};

// 导航到词条详情页的通用函数
const navigateToEntryWithId = (router, entryId) => {
  router.push({
    name: 'entryWithId',
    params: { entryId }
  });
};

// 发布词条
const handlePublish = async () => {
  const userStore = JSON.parse(sessionStorage.getItem("user"))
  // 判断是否登录（通过userStore中是否有用户信息）
  console.log("user信息：", userStore)
  if (!userStore || !userStore.userId) {
    alert('请先登录');
    router.push('/login'); // 跳转到登录页
    return;
  }

  if (!entriesForm.categoryId) {
    alert('请先选择分类');
    return;
  }
  if (!validateForm()) return;

  try {
    loading.value = true;
    // 构造请求数据（添加userId字段）
    const formData = {
      entryName: entriesForm.entryName.trim(),
      description: entriesForm.description.trim(),
      categoryId: entriesForm.categoryId,
      source: entriesForm.source.trim() || '',
      entriesPic: entriesForm.entriesPic || '',
      publishId: userStore.userId // 从userStore获取用户ID
    };

    // 调用后端接口（无需携带Authorization头）
    const res = await axios.post('api/entries/addEntries', formData);

    if (!isMounted.value) return;

    if (res.code === 200) {
      alert('发布成功');
      // 获取新发布词条的ID（假设后端返回的数据中包含entryId）
      const newEntryId = res.data.entryId;
      // 使用通用导航函数跳转到详情页
      navigateToEntryWithId(router, newEntryId);
    } else {
      alert(res.msg || '发布失败');
    }
  } catch (error) {
    console.error('发布失败:', error);
    alert('发布失败，请重试');
  } finally {
    loading.value = false;
  }
};
</script>

<style lang="less" scoped>
.entries-add-container {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 80px;
  position: relative;
}

.entries-add-header {
  background: linear-gradient(135deg, #07c160 0%, #05a85a 100%);

  :deep(.van-nav-bar__title) {
    color: white;
    font-weight: 600;
    font-size: 18px;
  }

  :deep(.van-nav-bar__left) {
    color: white;

    .van-icon {
      color: white;
    }
  }
}

.content-wrapper {
  padding: 16px;
  background-color: white;
  border-radius: 12px;
  margin: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
}

.publish-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-label {
  font-size: 16px;
  font-weight: 500;
  color: #323233;
}

.title-input {
  :deep(.van-cell) {
    padding: 12px 16px;
    border-radius: 8px;
    background-color: #f7f8fa;
    font-size: 16px;
  }

  :deep(.van-field__word-limit) {
    font-size: 12px;
    color: #969799;
  }
}

.category-field {
  :deep(.van-cell) {
    padding: 12px 16px;
    border-radius: 8px;
    background-color: #f7f8fa;
    font-size: 16px;
  }
}

.source-input {
  :deep(.van-cell) {
    padding: 12px 16px;
    border-radius: 8px;
    background-color: #f7f8fa;
    font-size: 16px;
  }

  :deep(.van-field__word-limit) {
    font-size: 12px;
    color: #969799;
  }
}

.content-input {
  :deep(.van-cell) {
    padding: 12px 16px;
    border-radius: 8px;
    background-color: #f7f8fa;
  }

  :deep(.van-field__control) {
    font-size: 16px;
    line-height: 1.6;
    min-height: 160px;
  }

  :deep(.van-field__word-limit) {
    font-size: 12px;
    color: #969799;
  }
}

.image-upload-section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.upload-btn {
  width: 100%;
  height: 120px;
  border: 2px dashed #dcdee0;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #969799;
  cursor: pointer;
  transition: all 0.3s ease;
  background-color: #f7f8fa;

  &:hover {
    border-color: #07c160;
    color: #07c160;
    background-color: rgba(7, 193, 96, 0.05);
  }

  span {
    margin-top: 8px;
    font-size: 14px;
  }
}

.image-preview {
  width: 100%;
  height: 180px;
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }

  .delete-icon {
    position: absolute;
    top: 8px;
    right: 8px;
    background-color: rgba(0, 0, 0, 0.5);
    color: white;
    width: 28px;
    height: 28px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: background-color 0.3s;

    &:hover {
      background-color: rgba(0, 0, 0, 0.7);
    }
  }
}

.footer-actions {
  position: fixed;
  bottom: 45px;
  left: 100px;
  right: 100px;
  padding: 16px;
}

.publish-btn {
  background: linear-gradient(135deg, #07c160 0%, #05a85a 100%);
  border: none;
  font-weight: 600;
  font-size: 16px;
  box-shadow: 0 4px 10px rgba(7, 193, 96, 0.3);

  &:active {
    opacity: 0.9;
  }
}

.loading-overlay {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;

  .van-loading__text {
    color: white;
    margin-top: 16px;
    font-size: 16px;
  }
}
</style>